package editvois

import (
	"bytes"
	"fmt"
	"html/template"
	"net/http"
	"os"

	"code.google.com/awwwe-browser/data"
)

// Builds the default view.
func HandlerDefault(w http.ResponseWriter, r *http.Request) {
	var pdata *PageData
	var err error
	var t *template.Template
	var cwd, msg string
	pdata = pageDataDefault()
	// page template
	t, err = template.ParseFiles(fmt.Sprintf("%s/siteLayout.tmpl", Package))
	if err == nil {
		err = t.Execute(w, pdata)
	}
	if err != nil {
		msg = err.Error()
		cwd, err = os.Getwd()
		errorOutString(w, fmt.Sprintf("%s<br/>%s", msg, cwd))
	}
}

// builds the view data for the default view.
func pageDataDefault() *PageData {
	var pdata *PageData
	pdata = newPageData(data.EmptyString, data.EmptyString)
	pdata.PageTitle = "Home"
	pdata.Layout = "_SiteLayout.tmpl"
	pdata.PageClass = "sitePage"
	pdata.HeaderClass = "awwwebrowsersite-header-home"
	pdata.BodyClass = "awwwebrowsersite-home"
	pdata.MainContentClass = "articleContent"
	// css urls
	pdata.CSSURL = template.URL(fmt.Sprintf(homeCssUrl, HomeURL))
	pdata.GeneralCSSURL = template.URL(fmt.Sprintf(generalCssUrl, HomeURL))
	pdata.NavCSSURL = template.URL(fmt.Sprintf(navCssUrl, HomeURL))
	pdata.FormCSSURL = template.URL(fmt.Sprintf(normalFormCssUrl, HomeURL))
	// link classe
	pdata.HomeLinkClass = "currentPageLink"
	// javascript
	pdata.HomeOnClick = currentOnClick
	// styles
	pdata.StyleFunc = homeStyleFunc

	var t *template.Template
	var err error
	var bfr *bytes.Buffer
	// head markup
	t, err = template.ParseFiles(fmt.Sprintf("%s/head.tmpl", Package))
	if err == nil {
		bfr = bytes.NewBuffer(data.EmptyBytes)
		err = t.Execute(bfr, pdata)
		if err == nil {
			pdata.HeadMarkup = template.HTML(bfr.String())
		} else {
			pdata.HeadMarkup = template.HTML(fmt.Sprintf("<!-- %s -->", err.Error()))
		}
	} else {
		pdata.HeadMarkup = template.HTML(fmt.Sprintf("<!-- %s -->", err.Error()))
	}
	// navigation markup
	t, err = template.ParseFiles(fmt.Sprintf("%s/navigation.tmpl", Package))
	if err == nil {
		bfr = bytes.NewBuffer(data.EmptyBytes)
		err = t.Execute(bfr, pdata)
		if err == nil {
			pdata.NavigationMarkup = template.HTML(bfr.String())
		} else {
			pdata.NavigationMarkup = template.HTML(fmt.Sprintf("NAV ERROR: %s", err.Error()))
		}
	} else {
		pdata.NavigationMarkup = template.HTML(fmt.Sprintf("NAV ERROR: %s", err.Error()))
	}
	// body markup
	t, err = template.ParseFiles(fmt.Sprintf("%s/default.tmpl", Package))
	if err == nil {
		bfr = bytes.NewBuffer(data.EmptyBytes)
		err = t.Execute(bfr, pdata)
		if err == nil {
			pdata.BodyMarkup = template.HTML(bfr.String())
		}
	}
	return pdata
}
